import sys

from PySide6.QtWidgets import QApplication

from qt.qtmenu import MainMenu
from qt.qtpref import SettingsWindow
from qt.qttray import MainSystemTray
from qt.qtwin import MainWindow
from utils.config import Settings
from utils.monitor import ClipboardMonitor, GlobalHotKeysManager


class App(QApplication):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 全局设置初始化
        self.settings = Settings()
        self.settings.read_config()

        # 组件初始化
        self.main_window = MainWindow(self)
        self.menu = MainMenu(self)
        self.settings_window = SettingsWindow(self)
        self.system_tray = MainSystemTray(self)

        # 监听剪贴板
        self.clipboard_monitor = ClipboardMonitor(self)
        self.clipboard_monitor.daemon = True
        self.clipboard_monitor.start()

        # 绑定全局热键
        self.global_hotkeys_manager = GlobalHotKeysManager(self)
        self.global_hotkeys_manager.daemon = True
        self.global_hotkeys_manager.start()

    def connect_slots(self):
        self.settings_window.connect_slots()
        self.menu.connect_slots()
        self.clipboard_monitor.connect_slots()
        self.global_hotkeys_manager.connect_slots()

    def quit(self):
        super().quit()

        self.settings_window.close()
        self.main_window.close()
        self.menu.close()

        self.clipboard_monitor.quit()
        self.clipboard_monitor.wait()

        self.global_hotkeys_manager.quit()
        self.global_hotkeys_manager.wait()


if __name__ == '__main__':
    app = App(sys.argv)  # 创建应用
    app.connect_slots()  # 连接槽函数
    app.main_window.show()  # 显示窗口
    sys.exit(app.exec())  # 进入消息循环
